package cn.donting.web.desktop.core.app;

import cn.donting.web.desktop.core.dao.AppInfoRepository;
import cn.donting.web.desktop.core.entity.AppInfo;
import cn.donting.web.desktop.core.evn.CoreProperties;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.io.File;
import java.nio.file.Files;

/**
 * 开发状态的AppManager
 * 主要加载  classpath的开发App
 */
@Slf4j
public class DevAppManager extends AppManager implements ApplicationRunner {


    @Autowired
    AppInfoRepository appInfoRepository;


    /**
     * 安装开发中的 app
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        File file = new File(CoreProperties.getSpace());
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()) {
                continue;
            }
//            if (file1.getName().equals("web-desktop-sys.classpath")) {
//                continue;
//            }
            if(file1.getName().endsWith(".classpath")){
                AppInfo byFileName = appInfoRepository.findByFileName(file1.getName());
                if (byFileName == null) {
                    log.info("install dev app :" + file1.getName());
                    super.install(file1, INSTALL_PATH+File.separator+file1.getName());
                    continue;
                }
                File installFile = new File(INSTALL_PATH+File.separator+file1.getName());
                //更新安装的文件
                log.info("update dev app :" +file1.getName());
                FileUtil.copy(file1, installFile, true);
            }
        }
    }
}
